<template>
  <div
    class="fs-dragball"
    :style="dragStyle"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @click="handleClick"
  >
    <van-icon
      name="music-o"
      :class="['fs-dragball_icon', isPlay ? 'fs-dragball_icon_active' : '']"
      v-if="currentMusic"
    ></van-icon>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, toRefs, type CSSProperties } from "vue";
import usePlayerStore from "@/store/playerStore";
import { showToast } from "vant";

const { currentMusic, isPlay } = toRefs(usePlayerStore());

const emit = defineEmits<{
  (e: "dragClick"): void;
}>();

const W_clientX = document.documentElement.clientWidth;
const dragState = reactive({
  startX: 0,
  startY: 0,
  moveX: 0,
  moveY: 0,
  endX: 0,
  endY: 0,
  isTouch: false,
});

const dragStyle = computed(
  () =>
    ({
      transform: `translate3d(${dragState.moveX}px,${dragState.moveY}px,0)`,
      transition: !dragState.isTouch ? "all 0.3s ease-in-out" : "",
    } as CSSProperties)
);

const handleTouchStart = (e: TouchEvent) => {
  dragState.isTouch = true;
  const { clientX, clientY } = e.touches[0];
  dragState.startX = clientX;
  dragState.startY = clientY;
};

const handleTouchMove = (e: TouchEvent) => {
  const { clientX, clientY } = e.touches[0];
  dragState.moveX = clientX - dragState.startX + dragState.endX + 5;
  dragState.moveY = clientY - dragState.startY + dragState.endY;
};

const handleTouchEnd = (e: TouchEvent) => {
  dragState.isTouch = false;
  const { clientX, clientY } = e.changedTouches[0];
  if (clientX > W_clientX / 2) {
    dragState.moveX = 0;
  } else {
    dragState.moveX = -W_clientX + 30;
  }
  dragState.endX = dragState.moveX;
  dragState.endY = dragState.moveY;
};
const handleClick = () => {
  currentMusic.value ? emit("dragClick") : showToast("暂无播放的歌曲");
};
</script>

<style scoped lang="scss">
.fs-dragball {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  background: rgba(0, 0, 0, 0.1);
  right: 0;
  top: 50%;
  z-index: 1001;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  user-select: none;
  touch-action: none;
  &_icon {
    font-size: 22px;
    color: #68c6bd;

    &_active {
      animation: musicrotate 2s linear infinite;
    }
  }

  &::after {
    position: absolute;
    content: "";
    width: 70%;
    height: 70%;
    top: 50%;
    left: 50%;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    transition: all 0.2s ease-in-out;
    z-index: -1;
  }
}

@keyframes musicrotate {
  0% {
    transform: rotateZ(0);
  }
  25% {
    transform: rotateZ(90deg);
  }
  50% {
    transform: rotateZ(180deg);
  }
  75% {
    transform: rotateZ(270deg);
  }
  100% {
    transform: rotateZ(360deg);
  }
}
</style>
